﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TSOL.Helpers
{
    public class SafeCache
    {
        private static object _cacheSetter = new object();
        private static Dictionary<string, object> _cacheLockList = new Dictionary<string, object>();

        public static object GetCacheLockObject(string key)
        {
            if (_cacheLockList.ContainsKey(key))
            {
                return _cacheLockList[key];
            }
            else
            {
                lock (_cacheSetter)
                {
                    if (!_cacheLockList.ContainsKey(key))
                    {
                        _cacheLockList.Add(key, new object());
                    }
                    return _cacheLockList[key];
                }
            }
        }

        public static void Invalidate(string key)
        {
            HttpContext.Current.Cache.Remove(key);
        }

        public static T Cache<T>(string key, Func<string, object> lockMapper, Func<string, T> filler) where T : class
        {
            T value = HttpRuntime.Cache[key] as T;
            if (value == null)
            {
                lock (lockMapper(key))
                {
                    value = HttpRuntime.Cache[key] as T;

                    if (value == null)
                    {
                        value = filler(key);
                        if (value != null)
                        {
                            Invalidate(key);
                            HttpRuntime.Cache.Add(key, value, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(48, 0, 0), System.Web.Caching.CacheItemPriority.Default, null);
                        }
                    }
                }
            }

            return value;
        }
    }
}